class Userskill < ActiveRecord::Base
  belongs_to :user
  belongs_to :skill
  
  validates_presence_of :user_id
  validates_presence_of :skill_id
  
  # This validation currently doesn't work, so we have to 
  # do a manual one, but this will soon be fixed in a future version of Rails
  validates_associated :user, :skill

  def self.exists?(user_id_to_test, skill_id_to_test)
    self.find_by_user_id_and_skill_id(user_id_to_test, skill_id_to_test) ? true : false
  end
  
  protected
    def validate
      errors.add(:user_id, "is invalid") unless User.find_by_id(user_id)
      errors.add(:skill_id, "is invalid") unless Skill.find_by_id(skill_id)
    end
    
    def validate_on_create
      errors.add_to_base("Already exists") if Userskill.exists?(user_id, skill_id)
    end
end
